import request from './request'

/**
 * 用户登录
 * @param {Object} data 登录信息
 * @returns {Promise}
 */
export function login(data) {
    return request({
        url: '/user/login',
        method: 'post',
        data
    }).then(res => {
        if (res.data) {
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('user', JSON.stringify({
                id: res.data.id,
                username: res.data.username,
                email: res.data.email,
                phone: res.data.phone,
                userType: res.data.userType
            }))
        }
        return res
    })
}

/**
 * 用户注册
 * @param {Object} data 注册信息
 * @returns {Promise}
 */
export function register(data) {
    return request({
        url: '/user/register',
        method: 'post',
        data
    }).then(res => {
        if (res.data) {
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('user', JSON.stringify({
                id: res.data.id,
                username: res.data.username,
                email: res.data.email,
                phone: res.data.phone,
                userType: res.data.userType
            }))
        }
        return res
    })
}

/**
 * 退出登录
 * @returns {Promise}
 */
export function logout() {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
}

/**
 * 重置密码请求
 * @param {Object} data - 重置密码参数 {email}
 * @returns {Promise}
 */
export function resetPassword(data) {
  return request({
    url: '/auth/password/reset',
    method: 'post',
    data
  })
}

/**
 * 获取当前用户信息
 * @returns {Promise}
 */
export function getUserInfo() {
  return request({
    url: '/user/profile',
    method: 'get'
  })
}

/**
 * 更新用户个人信息
 * @param {Object} data - 用户信息
 * @returns {Promise}
 */
export function updateUserProfile(data) {
    return request({
        url: '/user/profile',
        method: 'put',
        data
    }).then(res => {
        if (res.data) {
            // 更新本地存储的用户信息
            const userStr = localStorage.getItem('user')
            if (userStr) {
                const user = JSON.parse(userStr)
                const updatedUser = { ...user, ...data }
                localStorage.setItem('user', JSON.stringify(updatedUser))
            }
        }
        return res
    })
}

/**
 * 修改密码
 * @param {Object} data - {oldPassword, newPassword}
 * @returns {Promise}
 */
export function changePassword(data) {
    return request({
        url: '/user/password',
        method: 'put',
        data
    })
} 